package controlador;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import modelo.dominio.Documento;
import modelo.dominio.Historico;
import modelo.servicio.Documentos;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

public class EdicionDocumento extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        PrintWriter out = response.getWriter();
        String carpeta = "";
        if (isMultipart) {
            try {
                String nombreArchivo;
                List<FileItem> items = null;
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(10240);
                factory.setRepository(new File(SeccionControlador.getDirectorioTemporal()));
                ServletFileUpload upload = new ServletFileUpload(factory);
                try {
                    items = upload.parseRequest(request);
                } catch (FileUploadException ex) {
                    out.println("Error de Parsing:" + ex.getMessage());
                }
                getServletContext().log("hizo el parse");
                Documento docu = new Documento();
                //String valor = "", 
                        String clave = "", descripcion = "", precedente = "", carpetaFisica = "", arcc = "";
                for (int i = 0; i < items.size(); i++) {
                    getServletContext().log("entra al for");
                    FileItem item = (FileItem) items.get(i);
                    if (item.isFormField()) {
                        //out.println(item.getFieldName() + ": " + item.getString());
                        if (item.getFieldName().equals("clave")) {
                            clave = item.getString();
                        } else if (item.getFieldName().equals("descripcion")) {
                            descripcion = item.getString();
                        } else if (item.getFieldName().equals("carpeta_fisica")) {
                            carpetaFisica = item.getString();
                        } else if (item.getFieldName().equals("precedente")) {
                            precedente = item.getString();
                        }
                    } else {
                        docu = Documentos.instancia().obtenerPorId(clave);
                        if (!item.getName().equals("")) {

                            //------------- sin SBM
//                            File borrar = new File(docu.getRuta());
//                            borrar.delete();
                            //------------- con SBM
                            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(SeccionControlador.getUsuarioCIFS());
                            String path = "smb:" + docu.getRuta().replace("\\", "/");
                            SmbFile sFile = new SmbFile(path, auth);
                            sFile.delete();
                            //-------------
                            nombreArchivo   = clave;
                            carpeta         = docu.getSeccion().getIdSeccion().toString();
                            String fileName = item.getName();
                            int desde       = fileName.lastIndexOf(".") > 0 ? fileName.lastIndexOf(".") : fileName.length();
                            String ext      = fileName.substring(desde, fileName.length());
                            arcc = SeccionControlador.getDirectorioCarga() + carpeta + "\\" + nombreArchivo + ext;
                            docu.setRuta(arcc); //docu.setClave(nombreArchivo); 
                            //------------- sin SBM
//                            File fichero = new File(arcc);
//                            item.write(fichero);
                            //------------- con SBM
                            path = "smb:" + arcc.replace("\\", "/");
                            sFile = new SmbFile(path, auth);
                            SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
                            InputStream in = item.getInputStream();
                            byte[] buffer = new byte[SeccionControlador.getTamanioBuffer()];
                            int read;
                            while ((read = in.read(buffer, 0, SeccionControlador.getTamanioBuffer())) != -1) {
                                sfos.write(buffer, 0, read);
                            }
                            sfos.close();
                            in.close();
                            //-------------
                        } else {
                            arcc = docu.getRuta();
                        }
                    }
                }//del for
                docu.setDescripcion(descripcion);
                docu.setLugarFisico(carpetaFisica);
                docu.setRuta(arcc);
                if (!precedente.equalsIgnoreCase("NA")) {
                    docu.setPrecedente(Documentos.instancia().obtenerPorId(precedente));
                } else {
                    docu.setPrecedente(null);
                }
                docu.setHistorico(new Historico(request.getSession().getAttribute("sUsuario").toString()));
                Documentos.instancia().actualizar(docu);

                response.sendRedirect(getServletContext().getContextPath());
            } catch (Exception ex) {
                out.println(ex.getMessage());
            }
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}
